layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate', '$http', 'zmnUtils', 'layer', 'zmnSelect','element'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var layedit = layui.layedit;
    var laydate = layui.laydate;
    var $http = layui.$http;
    var zmnUtils = layui.zmnUtils;
    var configObj = json.obj;
    var robOrderObj = json.robOrderObj;
    // 无网格抢单配置对象
    var noGridRobOrderObj = json.noGridRobOrderObj;
    var engineerList =json.engineerList;
    let zmnSelect = layui.zmnSelect;
    var element = layui.element;

    var cityId;
    var cityName="";

    //判断是否点击添加规则按钮
    var sum =1;
    dealRobOrderConfigData(robOrderObj)
    // 点击取消
    $("button#cancel").click(function () {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);//关闭当前页
    });
    //添加规则下单时间段、预约时间段、剔除渠道、剔除品类、工程师类型可能会出现多个，放在数组中后续取值

    // 渠道列表
    zmnSelect.selectlChannelOnesTwos({
        channelOneSelectId: 'channelOneIdList',
        channelTwoSelectId: 'channelTwoIdList',
    }, {
        channelOneSelectId: {
            maxCount: 100, //下拉框中的最多选项数量
            selectedValues:robOrderObj.robOrderRelationList.length>0&&robOrderObj.robOrderRelationList[0].firstLevelChannel!=null
                            ?robOrderObj.robOrderRelationList[0].firstLevelChannel.split(","):[],
            remote: {
                events: {
                    extendParams: function () {
                        return {status: 2}
                    },
                }
            },
            events: {
                changed: function (values) {
                    console.log("========channelOneIdList==========");
                    console.log("已选中的值:" + values);
                }
            }
        },
        channelTwoSelectId: {
            maxCount: 100, //下拉框中的最多选项数量
            selectedValues:robOrderObj.robOrderRelationList.length>0&&robOrderObj.robOrderRelationList[0].secondLevelChannel?
                            robOrderObj.robOrderRelationList[0].secondLevelChannel.split(","):[],
            remote: {
                events: {
                    extendParams: function () {
                        return {status: 2}
                    },
                }
            },
            events: {
                changed: function (values) {
                    console.log("========channelTwoIdList==========");
                    console.log("已选中的值:" + values);
                }
            }
        }
    });

    //服务分类列表
    zmnSelect.selectlEcProdCategories({
        servCategSelectId: "ecServCategId",
        ecCategOneSelectId: "ecServCategOneIdList",
    }, {
        servCategSelectId: {
            selectedValues: robOrderObj.robOrderRelationList.length>0
            &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>0
            &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].serviceClassification!=null
                ?robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].serviceClassification.split(","):[],
            remote: {
                limitPermit: false,
            },
            events: {
                changed(values) {
                    console.log("==========ecServCategId=========");
                    console.log("已选中的值:" + values);
                }
            }
        },
        ecCategOneSelectId: {
            selectedValues: robOrderObj.robOrderRelationList.length>0
            &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>0
            &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].firstLevelProduct!=null
                ?robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].firstLevelProduct.split(","):[],
            remote: {
                limitPermit: false,
            },
            events: {
                changed(values) {
                    console.log("==========ecServCategOneIdList=========");
                    console.log("已选中的值:" + values);
                }
            }
        },
    });




    form.verify({
        percentVal: function (value, item) {
            if (value !== "") {
                if (Number(value) < 0) {
                    return '占比数值不能小于0';
                }
                if (Number(value) > 100) {
                    return '占比数值不能大于100';
                }
            }
        },
        reworkLimit: function (value, item) {
            if (value !== "" && value !== '0') {
                if (Number(value) < 0) {
                    return '最大返修单量不能小于0';
                }
                if (Number(value) > 1000000) {
                    return '最大返修单量不能大于1000000';
                }
                var r = /^[1-9]\d*$/;
                if (!r.test(value)) {
                    return '只能输入正整数，请重新输入';
                }
            }
        },
        numberLimit: function (value, item) {
            var r = /^[1-9]\d*$/;
            if (value != "" && !r.test(value)) {
                return '只能输入正整数，请重新输入';
            }
        },
        maxNoGridRobOrderLimit: function (value, item) {
            if (value !== "" && value !== '0') {
                if (Number(value) < 0) {
                    return '最小输入不能小于0';
                }
                if (Number(value) > 100) {
                    return '最大输入不能大于100';
                }
                var r = /^[1-9]\d*$/;
                if (!r.test(value)) {
                    return '只能输入1-100范围内正整数，请重新输入';
                }
            }
        },
        maxNoGridDistributeLimit: function (value, item) {
            if (value !== "" && value !== '0') {
                if (Number(value) < 5) {
                    return '最小输入不能小于5';
                }
                if (Number(value) > 100) {
                    return '最大输入不能大于100';
                }
                var r = /^[1-9]\d*$/;
                if (!r.test(value)) {
                    return '只能输入5-100范围内5的倍数的正整数，请重新输入';
                }
                if (value % 5 !== 0) {
                    return '只能输入5-100范围内5的倍数的正整数，请重新输入';
                }
            }
        },
        cancelTimeAfterLimit: function (value, item) {
            if (value !== "" && value !== '0') {
                if (Number(value) < 0) {
                    return '最小输入不能小于0';
                }
                if (Number(value) > 1000000) {
                    return '最大输入不能大于1000000';
                }
                var r = /^[1-9]\d*$/;
                if (!r.test(value)) {
                    return '只能输入正整数，请重新输入';
                }
            }
        }
    });
    $(document).on('click', '#addRules', function () {
        //新增规则
        let node = initRuleNode("", "", "","","");
        $("#dynamic").append(node);
        //新增再次渲染时间插件
        drawTimePlug()
        //渲染下拉框
        drawSelect('add');
        $("#addRules").hide();
        form.render();
    });
    $(document).on('click', '.delete', function () {
        $(this).closest('.layui-current-row').remove();
        //删除规则，字段id变化
        $("#addRules").show();
        //删除远端缓存下拉框id
        var deleteSelects = ["channelOneIdList1","channelTwoIdList1","ecServCategId2","ecServCategOneIdList2","ecServCategId3","ecServCategOneIdList3"];
        zmnSelect.deleteXmSelects(deleteSelects);
    });
    $(document).on('click', '.deleteProduct', function () {
        $(this).closest('.layui-product-row').remove();
        //删除规则，字段id变化
        $(".addProducts").show();
        var deleteSelects = ["ecServCategId1","ecServCategOneIdList1"];
        zmnSelect.deleteXmSelects(deleteSelects);
    });

    $(document).on('click', '.deleteProduct1', function () {
        $(this).closest('.layui-product-row1').remove();
        //删除规则，字段id变化
        $(".addProducts1").show();
        //删除远端缓存下拉框id
        var deleteSelects = ["ecServCategId3","ecServCategOneIdList3"];
        zmnSelect.deleteXmSelects(deleteSelects);

    });

    $(document).on('click', ".addProducts", function () {
            //新增品类
            let baseHtml = addProductsFunc();
            $(".productFlag").append(baseHtml);
            //再次渲染下拉框样式
            drawSelect1();
            $(".addProducts").hide();
    });

    function addProductsFunc(){
        let baseHtml =  '<div class="layui-card layui-product-row">\n' +
            '           <div class="layui-row">\n' +
            '               <div class="layui-col-sm10 layui-form">\n' +
            '                  <div class="layui-form-item" >\n' +
            '            <label class="layui-form-label "></label>\n' +
            '                      <div class="layui-input-inline" >\n' +
            '                          <div id="ecServCategId1"></div>\n' +
            '                      </div>\n' +
            '                      <div class="layui-input-inline" >\n' +
            '                          <div id="ecServCategOneIdList1"></div>\n' +
            '                      </div>\n' +
            '                  </div>\n' +
            '               </div>\n' +
            '           </div>\n' +
            '<div class="layui-row">\n' +
            '    <div class="layui-col-sm10 layui-form">\n' +
            '        <div class="layui-form-item" style="margin-top: 10px">\n' +
            '           <div   className="layui-input-block" > \n' +
            '                <a href="javascript:void(0)" class="deleteProduct" data-method="deleteProduct" style="text-decoration:underline;color: #00a0e9">删除</a>\n' +
            '           </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '    </div>\n' +
            '</div>';
        return baseHtml;
    }

    $(document).on('click', '.addProducts1', function () {
       let baseHtml = addProductsFunc1();
        $('.productFlag1').append(baseHtml);

        //再次渲染下拉框样式
        drawSelect3();
        form.render();
        $(".addProducts1").hide();
    });

    function addProductsFunc1(){
        let baseHtml =  '<div class="layui-card layui-product-row1">\n' +
            '           <div class="layui-row">\n' +
            '               <div class="layui-col-sm10 layui-form">\n' +
            '                  <div class="layui-form-item" >\n' +
            '            <label class="layui-form-label "></label>\n' +
            '                      <div class="layui-input-inline" >\n' +
            '                          <div id="ecServCategId3"></div>\n' +
            '                      </div>\n' +
            '                      <div class="layui-input-inline" >\n' +
            '                          <div id="ecServCategOneIdList3"></div>\n' +
            '                      </div>\n' +
            '                  </div>\n' +
            '               </div>\n' +
            '<div class="layui-row">\n' +
            '    <div class="layui-col-sm10 layui-form">\n' +
            '        <div class="layui-form-item" style="margin-top: 10px">\n' +
            '           <div   className="layui-input-block" > \n' +
            '                <a href="javascript:void(0)" class="deleteProduct1" data-method="deleteProduct1" style="text-decoration:underline;color: #00a0e9">删除</a>\n' +
            '           </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '    </div>\n' +
            '</div>';
        return baseHtml;
    }




    function drawTimePlug(){
        lay('.orderTimeStr1').each(function () {
            laydate.render({
                elem: this,
                type: 'time'
                , range: '~'
                , format: 'HH:mm'
                , trigger: 'click'
            });
        });
        lay('.appointmentTimeStr1').each(function () {
            laydate.render({
                elem: this,
                type: 'time'
                , range: '~'
                , format: 'HH:mm'
                , trigger: 'click'
            });
        });
        lay('.robOrderTimeStr1').each(function () {
            laydate.render({
                elem: this,
                type: 'time'
                , range: '~'
                , format: 'HH:mm'
                , trigger: 'click'
            });
        });
    }

    function drawSelect(flag){
        var selectedValues1=[];
        var selectedValues2=[];
        var selectedValues3=[];
        var selectedValues4=[];
        if(flag=='edit'){
            selectedValues1 =robOrderObj.robOrderRelationList.length>1&&robOrderObj.robOrderRelationList[1].firstLevelChannel!=null
                                ?robOrderObj.robOrderRelationList[1].firstLevelChannel.split(","):[];
            selectedValues2 =robOrderObj.robOrderRelationList.length>1&&robOrderObj.robOrderRelationList[1].secondLevelChannel!=null
                                ?robOrderObj.robOrderRelationList[1].secondLevelChannel.split(","):[];
            selectedValues3 =robOrderObj.robOrderRelationList.length>1
                                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>0
                                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].serviceClassification!=null
                                    ?robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].serviceClassification.split(","):[];
            selectedValues4 = robOrderObj.robOrderRelationList.length>1
                                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>0
                                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].firstLevelProduct!=null
                                    ?robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].firstLevelProduct.split(","):[];
        }
        //再次渲染下拉框样式
        zmnSelect.selectlChannelOnesTwos({

            channelOneSelectId: "channelOneIdList1",
            channelTwoSelectId: "channelTwoIdList1",
        }, {
            channelOneSelectId: {
                maxCount: 100, //下拉框中的最多选项数量
                selectedValues:selectedValues1,
                remote: {
                    events: {
                        extendParams: function () {
                            return {status: 2}
                        },
                    }
                },
                events: {
                    changed: function (values) {
                        console.log("========channelOneIdList2==========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
            channelTwoSelectId: {
                maxCount: 100, //下拉框中的最多选项数量
                selectedValues:selectedValues2,
                remote: {
                    events: {
                        extendParams: function () {
                            return {status: 2}
                        },
                    }
                },
                events: {
                    changed: function (values) {
                        console.log("========channelTwoIdList2==========");
                        console.log("已选中的值:" + values);
                    }
                }
            }
        });
        zmnSelect.selectlEcProdCategories({
            servCategSelectId: "ecServCategId2",
            ecCategOneSelectId: "ecServCategOneIdList2",
        }, {
            servCategSelectId: {
                selectedValues: selectedValues3,
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategId=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
            ecCategOneSelectId: {
                selectedValues: selectedValues4,
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategOneIdList=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
        });
    };

    function drawSelect1(){
        zmnSelect.selectlEcProdCategories({
            servCategSelectId: "ecServCategId1",
            ecCategOneSelectId: "ecServCategOneIdList1",
        }, {
            servCategSelectId: {
                selectedValues:  robOrderObj.robOrderRelationList.length>0
                &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>1
                &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].serviceClassification!=null
                    ?robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].serviceClassification.split(","):[],
                remote: {
                     limitPermit: true,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategId=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
            ecCategOneSelectId: {
                selectedValues: robOrderObj.robOrderRelationList.length>0
                &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>1
                &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].firstLevelProduct!=null
                    ?robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].firstLevelProduct.split(","):[],
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategOneIdList=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
        });
    }
    function  drawSelect3(){
        zmnSelect.selectlEcProdCategories({
            servCategSelectId: "ecServCategId3",
            ecCategOneSelectId: "ecServCategOneIdList3",
        }, {
            servCategSelectId: {
                selectedValues:robOrderObj.robOrderRelationList.length>1
                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>1
                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].serviceClassification!=null
                    ?robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].serviceClassification.split(","):[],
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategId=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
            ecCategOneSelectId: {
                selectedValues: robOrderObj.robOrderRelationList.length>1
                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>1
                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].firstLevelProduct!=null
                    ?robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].firstLevelProduct.split(","):[],
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategOneIdList=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
        });
    }




    function initRuleNode(orderTimeVal, appointmentTimeVal, robOrderTimeVal,engineerTypeVal,relationId) {

        let baseHtml = '<div class="layui-card layui-current-row"><hr><hr/>\n' +
            '        <div class="layui-card-header layui-select-row">工单设置：</span></div>\n' +
            '            <div class="layui-row" style="display: none">\n' +
            '                <div class="layui-col-sm10 layui-form">\n' +
            '                    <div class="layui-form-item">\n' +
            '                        <label class="layui-form-label layui-form-required">relationId:</label>\n' +
            '                        <div class="layui-input-inline">\n' +
            '                            <input  type="text" value="' + relationId + '" name="relationId1" \n' +
            '                                   class="layui-input"/>\n' +
            '                        </div>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n'+
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item">\n' +
            '                    <label class="layui-form-label">下单时间段:</label>\n' +
            '                    <div class="layui-input-inline">\n' +
            '                        <input value="' + orderTimeVal + '" type="text"\n' +
            '                               name="orderTimeStr1"\n' +
            '                               class="layui-input orderTimeStr1"/>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item">\n' +
            '                    <label class="layui-form-label ">预约时间段:</label>\n' +
            '                    <div class="layui-input-inline">\n' +
            '                        <input value="' + appointmentTimeVal + '" type="text"\n' +
            '                               name="appointmentTimeStr1"\n' +
            '                               class="layui-input appointmentTimeStr1"/>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '<div class="layui-row">\n' +
            '    <div classN="layui-col-sm10 layui-form">\n' +
            '        <div class="layui-form-item layui-form"  lay-filter="one">\n' +
            '            <label class="layui-form-label ">剔除渠道：</label>\n' +
            '            <div class="layui-input-inline" >\n' +
            '                <div id="channelOneIdList1"  ></div>\n' +
            '            </div>\n' +
            '            <div class="layui-input-inline">\n' +
            '                <div id="channelTwoIdList1" ></div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '</div>\n' +
            '<div class="layui-row">\n' +
            '    <div classN="layui-col-sm10 layui-form">\n' +
            '        <div class="layui-form-item layui-form"  lay-filter="one">\n' +
            '            <label class="layui-form-label ">剔除品类：</label>\n' +
            '            <div class="layui-input-inline" >\n' +
            '                <div id="ecServCategId2" ></div>\n' +
            '            </div>\n' +
            '            <div class="layui-input-inline">\n' +
            '                <div id="ecServCategOneIdList2" ></div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '  <div  class="productFlag1"></div>\n' +
            '            <div class="layui-input-block">\n' +
            '                <a  href="javascript:void(0)"  class="addProducts1"\n' +
            '                   style="text-decoration:underline;color: #00a0e9">+添加</a>\n' +
            '            </div>\n' +
            '</div>\n' +
            '        <div class="layui-card-header">工程师设置：</span></div>\n' +
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item" style="margin-top: 10px">\n' +
            '                    <label class="layui-form-label layui-form-required">工程师类型:</label>\n' +
            '                    <div class="layui-input-inline">\n' +
            '                        <select  name="engineerType1" lay-verify="required"\n' +
            '                                lay-search=""\n' +
            '                                 autocomplete="off">\n' +drawList(engineerTypeVal)+
            '                        </select>\n' +
            '                    </div>\n' +
            '                    <div class="layui-form-mid layui-word-aux">当仅有此类型工程师时，工单将按抢单方式分配</div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '<div className="layui-card-header">抢单时间:</div>\n' +
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item">\n' +
            '                    <label class="layui-form-label layui-form-required">抢单时间:</label>\n' +
            '                    <div class="layui-input-inline">\n' +
            '                        <input  value="' + robOrderTimeVal + '" lay-verify="required" type="text"\n' +
            '                               name="robOrderTimeStr1"\n' +
            '                               class="layui-input robOrderTimeStr1"/>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item" style="margin-top: 10px">\n' +
            '                    <div   className="layui-input-block" >\n' +
            '                <a href="javascript:void(0)" class="delete" data-method="delete" style="text-decoration:underline;color: #00a0e9">删除规则</a>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '    </div>';
        return baseHtml;
    }

    function drawList(engineerTypeVal){
        var optionHtml='';
        if(engineerTypeVal==""){
            optionHtml = '<option value="">请选择工程师</option>'
        }
        for (var i = 0; i < engineerList.length; i++) {
            if (engineerList[i]['key']===engineerTypeVal) {
                optionHtml += '<option value="' + engineerList[i]['key'] + '" selected>' + engineerList[i]['value'] + '</option>';
            } else {
                optionHtml += '<option value="' + engineerList[i]['key'] + '">' + engineerList[i]['value'] + '</option>';
            }

        }
        return optionHtml;
    }


    // 是否为正整数
    function isPositiveInteger(number) {
        var re = /^[0-9]\d*$/;
        return re.test(number)
    }
    //后者时间大于前者
    function checkDate(t1,t2){
        var date = new Date();
        var a = t1.split(":");
        var b = t2.split(":");
        if (parseInt(a[0])>parseInt(b[0])) {
            return true;
        }
        if (parseInt(a[0])==parseInt(b[0])&&parseInt(a[1])>=parseInt(b[1])) {
            return true;
        }
        return false;
    }

    // 比较两个时间的先后
    function compareDate(t1, t2) {
        var date = new Date();
        var a = t1.split(":");
        if (a[0] < 0 || a[0] > 23) {
            return true;
        }
        if (a[1] < 0 || a[1] > 59) {
            return true;
        }
        var b = t2.split(":");
        if (b[0] < 0 || b[0] > 23) {
            return true;
        }
        if (b[1] < 0 || b[1] > 59) {
            return true;
        }
        return date.setHours(a[0], a[1]) > date.setHours(b[0], b[1]);
    }

    form.on('submit(zmn-rob-order-form-submit)', function (obj) {
        console.log("zmn-rob-order-form-submit")
        var data = obj.field;
        data.bizType = configObj.bizType;
        data.distributeWay=configObj.distributeWay;
        let robOrderRelationList = [];
        let find = $("#dynamic").find(".layui-current-row");
        let robOrderRelationProductList1 = [];

                if(obj.field["ecServCategId"]!=""&&obj.field["ecServCategId"]!=null&&obj.field["ecServCategId"]!=undefined){
                    let robOrderRelationProduct = {
                        relationProductId: robOrderObj.robOrderRelationList.length>0
                                             &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>0
                                             &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].relationProductId!=null?
                                                robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].relationProductId:null,
                        serviceClassification:obj.field["ecServCategId"],
                        firstLevelProduct:obj.field["ecServCategOneIdList"],
                    }
                    robOrderRelationProductList1.push(robOrderRelationProduct);
                }
               if(obj.field["ecServCategId1"]!=""&&obj.field["ecServCategId1"]!=null&&obj.field["ecServCategId1"]!=undefined){
                   let  robOrderRelationProduct = {
                       relationProductId: robOrderObj.robOrderRelationList.length>0
                       &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>1
                       &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].relationProductId!=null?
                           robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].relationProductId:null,
                       serviceClassification:obj.field["ecServCategId1"],
                       firstLevelProduct:obj.field["ecServCategOneIdList1"],
                   }
                   if(obj.field["ecServCategId1"]==obj.field["ecServCategId"]){
                       layer.msg('同一个规则组服务分类不能重复!');
                       return false;
                   }
                   robOrderRelationProductList1.push(robOrderRelationProduct);
               }


        let robOrderRelation = {
            relationId: obj.field["relationId"],
            orderTimeStr: obj.field["orderTimeStr"],
            appointmentTimeStr:obj.field["appointmentTimeStr"],
            robOrderTimeStr: obj.field["robOrderTimeStr"],
            engineerType:obj.field["engineerType"],
            firstLevelChannel:obj.field["channelOneIdList"],
            secondLevelChannel:obj.field["channelTwoIdList"],
            robOrderRelationProductList:robOrderRelationProductList1

        };
        robOrderRelationList.push(robOrderRelation);

        let robOrderRelationProductList2 = [];

                if(obj.field["ecServCategId2"]!=""&&obj.field["ecServCategId2"]!=null&&obj.field["ecServCategId2"]!=undefined){
                    let robOrderRelationProduct = {
                        relationProductId: robOrderObj.robOrderRelationList.length>1
                        &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>0
                        &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].relationProductId!=null?
                            robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].relationProductId:null,
                        serviceClassification:obj.field["ecServCategId2"],
                        firstLevelProduct:obj.field["ecServCategOneIdList2"],
                    }
                    robOrderRelationProductList2.push(robOrderRelationProduct);
                }
                if(obj.field["ecServCategId3"]!=""&&obj.field["ecServCategId3"]!=null&&obj.field["ecServCategId3"]!=undefined){
                   let robOrderRelationProduct = {
                       relationProductId: robOrderObj.robOrderRelationList.length>1
                       &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>1
                       &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].relationProductId!=null?
                           robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].relationProductId:null,
                       serviceClassification:obj.field["ecServCategId3"],
                       firstLevelProduct:obj.field["ecServCategOneIdList3"],
                    }
                    if(obj.field["ecServCategId2"]==obj.field["ecServCategId3"]){
                        layer.msg('同一个规则组服务分类不能重复!');
                        return false;
                    }
                    robOrderRelationProductList2.push(robOrderRelationProduct);
                }
        let compareOrderTime = false;
        let compareRobOrderTime = false;
        find.each(function (index, value) {
            let orderTimeStr = $(value).find("[name='orderTimeStr1']").val();
            if(orderTimeStr===(obj.field["orderTimeStr"])){
                compareOrderTime = true;
            }

            let appointmentTimeStr = $(value).find("[name='appointmentTimeStr1']").val();
            let robOrderTimeStr = $(value).find("[name='robOrderTimeStr1']").val();
            if( obj.field["robOrderTimeStr"]===(robOrderTimeStr)){
                compareRobOrderTime =true;
            }
            let relationId = $(value).find("[name='relationId1']").val();
            let engineerType = $(value).find("[name='engineerType1']").val();
            let robOrderRelation = {
                relationId: relationId,
                orderTimeStr: orderTimeStr,
                appointmentTimeStr:appointmentTimeStr,
                robOrderTimeStr: robOrderTimeStr,
                engineerType:engineerType,
                firstLevelChannel:obj.field["channelOneIdList1"],
                secondLevelChannel:obj.field["channelTwoIdList1"],
                robOrderRelationProductList:robOrderRelationProductList2
            };
            robOrderRelationList.push(robOrderRelation);
        });
        if(compareOrderTime){
            layer.msg('各规则的下单时间不可重合!');
            return false;
        }
        if(compareRobOrderTime){
            layer.msg('各规则的抢单时间不可重合!');
            return false;
        }
        data.robOrderRelationList=robOrderRelationList;
        //目前仅针对啄木鸟平台
        data.plat=10;
        data.provinceId=data.robOrderProvinceId;
        data.cityId=data.robOrderCityId;
        data.provinceName = robOrderProvince==undefined?"":robOrderProvince.getValue()[0].name;
        data.cityName = robOrderCity==undefined?"":robOrderCity.getValue()[0].name;

        let checkOrderTime = false;
        let checkAppointmentTime = false;
        let checkRobOrderTime = false;
        if(robOrderRelationList!=null&&robOrderRelationList.length>0){

            robOrderRelationList.forEach(item => {
                //校验时间
                if(item.orderTimeStr!=""&&(checkDate(item.orderTimeStr.split("~")[0],item.orderTimeStr.split("~")[1]))){

                    checkOrderTime = true;
                }
                if(item.appointmentTimeStr!=""&&(checkDate(item.appointmentTimeStr.split("~")[0],item.appointmentTimeStr.split("~")[1]))){
                    checkAppointmentTime = true;
                }
                if(item.robOrderTimeStr!=""&&(checkDate(item.robOrderTimeStr.split("~")[0],item.robOrderTimeStr.split("~")[1]))){
                    checkRobOrderTime =true;
                }
            });
        }
        // if(checkOrderTime){
        //     layer.msg('下单结束时间必须大于开始时间!');
        //     return false;
        // }
        // if(checkAppointmentTime){
        //     layer.msg('预约结束时间必须大于开始时间!');
        //     return false;
        // }
        // if(checkRobOrderTime){
        //     layer.msg('抢单结束时间必须大于开始时间!');
        //     return false;
        // }

        var url = "";
        //configId为空是新增，先将数据存入缓存；configId不为空走更新，直接写入数据库
        if(robOrderObj.configId==null||robOrderObj.configId==undefined||robOrderObj.configId==""){
            url = "/conf/distribute/plat/setRobOrderConfigDataToRedis";
            $http.save(url, data).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    //城市id信息改为全局变量，最后提交使用
                    cityId = data.cityId;
                    cityName = data.cityName;

                    //切换到：派单管理
                     element.tabChange('changeSecondTab', 'sendOrderId');
                    // 切换到 返修单
                    //element.tabChange('changeFirstTab', 'repairOrderId');
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
            });
        }else{
            data.configId=robOrderObj.configId;
            url ="/conf/distribute/plat/robOrder/modifyOrInsert"
            $http.save(url, data).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    // var index = parent.layer.getFrameIndex(window.name);
                    // parent.layer.close(index);
                    // window.parent.location.reload();
                    window.location.reload();
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
            });
        }

        return false;

    });

    // 无网格抢单提交
    form.on('submit(zmn-noGrid-rob-order-form-submit)', function (obj) {
        console.log("zmn-noGrid-rob-order-form-submit");
        let data = obj.field;
        data.engineerType = data.engineerTypeOf;
        data.bizType = configObj.bizType;
        data.distributeWay = configObj.distributeWay;
        data.plat = 10;
        data.provinceId = data.noGridRobOrderProvinceId;
        data.cityId = data.noGridRobOrderCityId;
        data.provinceName = noGridRobOrderProvince == undefined ? "" : noGridRobOrderProvince.getValue()[0].name;
        data.cityName = noGridRobOrderCity == undefined ? "" : noGridRobOrderCity.getValue()[0].name;

        let tempEngineerSource = "";
        if ($("#engineerCompanyTypeOfOne").prop("checked") && $("#engineerCompanyTypeOfTwo").prop("checked")) {
            tempEngineerCompanyType = "1,2,";
        } else if (!$("#engineerCompanyTypeOfOne").prop("checked") && !$("#engineerCompanyTypeOfTwo").prop("checked")) {
            layer.alert('工程师设置必须至少选择一个');
            return false;
        } else if ($("#engineerCompanyTypeOfOne").prop("checked")) {
            tempEngineerCompanyType = "1,";
        } else if ($("#engineerCompanyTypeOfTwo").prop("checked")) {
            tempEngineerCompanyType = "2,";
        }
        data.engineerCompanyType = tempEngineerCompanyType;
        // 处理下抢单状态字段
        if (!data.hasOwnProperty('robOrderStatus')) {
            data.robOrderStatus = 1;
        }

        // 验证省市ID和城市ID
        let distributeOfProvinceId = configObj.provinceId;
        let distributeOfCityId = configObj.cityId;
        if (configObj.distributePlatId != null) {
            if (distributeOfProvinceId !== Number(data.provinceId) || distributeOfCityId !== Number(data.cityId)) {
                layer.msg("省市ID或城市ID与派单规则不一致")
                return false;
            }
        }

        //保存数据库
        data.nonGridConfigId = noGridRobOrderObj.nonGridConfigId;
        let url = "/conf/distribute/plat/noGridRobOrder/modifyOrInsert"
        $http.save(url, data).then(function () {
            zmnUtils.layui.toastSuccess('成功', function () {
                // var index = parent.layer.getFrameIndex(window.name);
                // parent.layer.close(index);
                // window.parent.location.reload();
                window.location.reload();
            })
        }, function (msg) {
            zmnUtils.layui.toastError(msg);
        });

        // 阻止表单默认跳转
        return false;
    })
    // 无网格补充
    let cancelTimeAfter = document.getElementById("cancelTimeAfter");
    cancelTimeAfter.addEventListener("keyup", function () {
        let value = cancelTimeAfter.value;
        if (value !== "" && value !== '0') {
            let r = /^[1-9]\d*$/;
            if (value > 0 && r.test(value)) {
                let spanTip = document.getElementById("spanTip");
                spanTip.innerText = value;
            }
        }
    })

    // 校验多轮保护规则
    $(document).on("blur", '.ruleNumber', function () {
        if (!isNumberAnd1To99($(this).val())) {
            layer.msg("请输入1-99范围内的整数");
            $(this).val("");
            return;
        }
    });


    // 提交的时候正式校验   passRule: [/^[1-9]{0,1}[0-9]{0,1}$/, "多轮规则保护必须为数字且大小为大于等于0小于等于99"],
    form.verify({
        engineerMaxDistanceVerify: function (value) {
            if ($("input[name='acrossDistributeStatus']").attr("checked") === "checked") {
                if (value === "") {
                    return "必填项不能为空";
                }
            }
        },
        supportGridCountLimitVerify: function (value) {
            if (value === "") {
                $("input[name='supportGridCountLimit']").val(0);
                return "工程师必绑支网格配置不能为空";
            }

            if (value < 0) {
                $("input[name='supportGridCountLimit']").val(0);
                return "工程师必绑支网格数必须等于或大于 0";
            }

            // 正整数，不包含小数正则
            let interNumberRule = /^[0-9]\d*$/;
            if (!interNumberRule.test(value)) {
                $("input[name='supportGridCountLimit']").val(0);
                return "工程师必绑支网格数必须为正整数";
            }

        }
    });

    // 基于推荐自动派  首轮保护和多轮保护
    form.on('radio(autoStatusNew)',function (obj) {
        var dom = obj.elem;

        var tit1 = $(dom).attr("title");

        if("推荐自动派" == tit1){
            $("#autoStatusNewSave").show();
            if($("input[title='多轮保护']").attr("checked") == 'checked'){
                $(".manySaveParam").show();
            }
        }else{
            console.log("-----------------")
            $(".chanping1").each(function () {
                $(this).val("");
            });
            $("#autoRuleStr").val("");
            $("input[title='首轮保护']").attr("checked","checked");
            $("input[title='多轮保护']").removeAttr("checked");
            form.render('radio');
            $("input[data-name='首轮保护']").prop("checked", true);
            $("input[data-name='多轮保护']").prop("checked", false);
            form.render("checkbox");//重新渲染页面checkbox控件
            $("#autoStatusNewSave").hide();
            $(".manySaveParam").hide();
        }
    });

    // 基于推荐自动派  首轮保护和多轮保护
    form.on('radio(autoRecommendProtectionType)',function (obj) {
        var dom = obj.elem;

        var tit1 = $(dom).attr("title");


        if("多轮保护" == tit1){
            $("input[title='多轮保护']").attr("checked","checked");
            $("input[title='首轮保护']").removeAttr("checked");
            $(".manySaveParam").show();
        }else{
            $("input[title='首轮保护']").attr("checked","checked");
            $("input[title='多轮保护']").removeAttr("checked");
            $(".manySaveParam").hide();
        }
    });

    // 基于推荐自动派  首轮保护和多轮保护
    form.on('checkbox(autoRecommendProtectionTypeCheckbox)',function (obj) {
        var dom = obj.elem;
        if(dom.checked){
            $("input[title='多轮保护']").attr("checked","checked");
            $("input[title='首轮保护']").removeAttr("checked");
            $(".manySaveParam").show();
        }else{
            $("input[title='首轮保护']").attr("checked","checked");
            $("input[title='多轮保护']").removeAttr("checked");
            $(".manySaveParam").hide();
        }
    });



    // 应用多产品组消息
    form.on('checkbox(allTimeSave)', function(data){
        //console.log(data.elem); //得到checkbox原始DOM对象
        //console.log(data.elem.checked); //开关是否开启，true或者false
        //console.log(data.value); //开关value值，也可以通过data.elem.value得到
        //console.log(data.othis); //得到美化后的DOM对象
        var check = data.elem.checked;
        if(check){
            var allValue = $("#autoTimeStr").val();
            $(".chanping2").each(function () {
                $(this).val(allValue);
            })
        }
    });

    /**
     * 多轮保护 - 默认次数应用当前产品组事件
     */
    // form.on('checkbox(allRuleSave)', function (data) {
    //     let applyToAllCheckboxElement = $(data.elem);
    //     // 获取多轮保护的类型
    //     let protectionType = applyToAllCheckboxElement.attr("data-protection-type")
    //     if (data.value) {
    //         // 让【当前多轮保护类型】下的【所有产品组】的【保护次数】，都设为【当前多轮保护类型】的【默认次数】
    //         $("#product-group-" + protectionType + " .chanping1").each(function () {
    //             $(this).val($(".default-times-" + protectionType).val());
    //         })
    //     }
    // });

    // 跨网格派 开启/关闭
    form.on('switch(acrossTablePlatSwitch)', function (data) {
        var acrossTableChecked = data.elem;
        if (data.elem.checked) {
            $(acrossTableChecked).attr("checked", "checked");
            $('input[name="acrossMaxTakeDistance"]').removeAttr("disabled");
            $('input[name="acrossMaxDistributeDistance"]').removeAttr("disabled");
            $('input[name="acrossDistributeWaitTime"]').removeAttr("disabled");
        } else {
            $(acrossTableChecked).removeAttr("checked");
            $('input[name="acrossMaxTakeDistance"]').attr("disabled", "disabled");
            $('input[name="acrossMaxDistributeDistance"]').attr("disabled", "disabled");
            $('input[name="acrossDistributeWaitTime"]').attr("disabled", "disabled");
        }
    });

    // 失去焦点校验 跨网格派单工程师最大接单距离
    $('input[name="acrossMaxTakeDistance"]').blur(function () {
        var engineerMaxNum = parseInt($(this).val());
        var engineerMaxBool = !isNaN(engineerMaxNum);
        if (engineerMaxBool && (engineerMaxNum < 1 || engineerMaxNum > 100)) {
            layer.msg("请输入1-100范围内的整数");
            $(this).val("");
        }
    });

    // 失去焦点校验 跨网格派单最大距离
    $('input[name="acrossMaxDistributeDistance"]').blur(function () {
        var platMaxNum = parseInt($(this).val());
        var platMaxBool = !isNaN(platMaxNum);
        if (platMaxBool && !(platMaxNum < 5 || platMaxNum > 100)) {
            if (platMaxNum % 5) {
                layer.msg("请输入5-100范围内5的倍数的整数");
                $(this).val("");
            }
        } else if ($(this).val() !== "") {
            layer.msg("请输入5-100范围内5的倍数的整数");
            $(this).val("");
        }
    });

    // 失去焦点校验 跨网格派单等待时间
    $('input[name="acrossDistributeWaitTime"]').blur(function () {
        var watiTimeNum = parseInt($(this).val());
        var watiTimeBool = !isNaN(watiTimeNum);
        if (watiTimeBool && watiTimeNum < 0) {
            layer.msg("请输入大于或等于0的整数");
            $(this).val("");
        }
        $(this).val(watiTimeNum);
    });


    /**
     * 获取多轮保护的产品组
     *
     * @param protectType 多轮保护类型 1.普通 2.优先
     * @returns {string}
     */
    function getProductGroupTimes(protectType) {

        // 是否选择了多轮保护
        let isMultipleRoundsProtection = $("input[name='autoRecommendProtectionType'][value='2']").attr("checked") == "checked";

        // 多轮优先 - 产品组对应规则
        let productGroupTimes = {};
        $("#product-group-" + protectType + " .chanping1").each(function () {
            if (isMultipleRoundsProtection) {
                productGroupTimes[$(this).attr("name")] = $(this).val();
            } else {
                productGroupTimes[$(this).attr("name")] = '';
            }
        })
        return JSON.stringify(productGroupTimes);
    }

    // 保存服务商信息
    form.on('submit(zmn-form-submit)', function (obj) {

        var data = obj.field;
        data.bizType = configObj.bizType;

        // 跨网格派
        if($("input[name='acrossDistributeStatus']").attr("checked") === "checked"){
            data.acrossDistributeStatus = 2;
        }

        // 平台指派且选择推荐自动派的 若未选择多轮 默认选中传输首轮
        if (obj.distributeWay == 10 && obj.autoStatusNew == 2 && (data.autoRecommendProtectionType == null || data.autoRecommendProtectionType == undefined)) {
            data.autoRecommendProtectionType = 1;
        }

        // 不是推荐自动派 默认保护就是首轮
        if (data.autoStatusNew !== "2" && data.hasOwnProperty('autoRecommendProtectionType')){
            data.autoRecommendProtectionType = 1;
        }

        /* 多产品组信息 */

        // 首轮配置
        data.protectionFirstProductGroupJson = getters.getFirstProtectionLevelsJsonStr();

        // 多轮普通 - 每个产品组保护次数
        data.protectionTimesProductGroupJson = getters.getProtectionJSONStr(getters.protectionTableId);

        // 多轮优先 - 每个产品组保护次数
        data.priorityProtectionTimesProductGroup = getters.getProtectionJSONStr(getters.priorityProtectionTableId);

        // 多轮优先 某个产品组是否指定了保护次数
        let hasProtectionTimesProductGroup = Object.values(data.priorityProtectionTimesProductGroup).some(value => {
            // 只要【多个产品】组中【有一个产品组】的值不为空，就设置为true
            if (value != "") {
                return true
            }
        })
        // 多轮优先保护状态 1.没有多轮优先保护 2.有多轮优先保护
        data.priorityProtectionStatus = hasProtectionTimesProductGroup ? 2 : 1;

        // 多个产品组对应派单时间
        var productGroupTime = {};
        $(".chanping2").each(function () {
            productGroupTime[$(this).data("id")] = $(this).val();
        })
        data.autoTimeProductGroupJson = JSON.stringify(productGroupTime);

        // 未开启多轮保护 多轮保护默认值为 null
        if ($("input[title='多轮保护']").attr("checked") != "checked"){
            data.protectionDefaultTimes = "";
            data.priorityProtectionDefaultTimes = "";
        }

        // 如果是推荐自动派且开启多轮保护校验默认次数不能为空
        if (data.autoStatusNew === "2") {
            if ($("input[title='多轮保护']").attr("checked") === "checked") {
                if ($("#autoRuleStr").val() == "") {
                    layer.msg("多轮普通的默认值不能为空");
                    return false;
                }
            }
        }

        // 分级准入
        if (data.engineerLevelStatus == '2') {
            // if (data.engineerLevelGroupStatus != '2') {
            //     layer.msg("必须开启分级保护！");
            //     return false;
            // }

            data.engineerLevels = getters.getEngineerLevels();
            if (!data.engineerLevels) {
                layer.msg("未配置工程师等级！");
                return false;
            }
        } else {
            data.engineerLevels = '';
        }

        // 分级保护参数校验
        let resultData = getters.getEngineerLevelGroupListJsonStr(data.engineerLevelGroupStatus);
        if (resultData) {
            if (resultData.msg) {
                layer.msg(resultData.msg);
                return false;
            }
            if (resultData.engineerLevelGroupListJsonStr) {
                data.engineerLevelGroupListJson = resultData.engineerLevelGroupListJsonStr;
            }
        }

        // 时间格式校验
        let autoTimeStr = data.autoTimeStr;
        let timeArr = autoTimeStr.split(' ~ ');
        if (compareDate(timeArr[0], timeArr[1])) {
            layer.msg('时间格式不正确!');
            return false;
        }
        let roundsEnable = data.roundsEnable;
        let nonDirectCount = data.nonDirectCount;
        let directSaleCount = data.directSaleCount;
        if (roundsEnable == "on") {
            data.roundsEnable = 2;
            if (nonDirectCount == "" || directSaleCount == "") {
                layer.msg("轮次开关开启，比例数值必填", {"icon": 2});
                return false;
            }
        } else {
            data.roundsEnable = 1;
        }
        let distributeWeightRelationList = [];
        let checkNan = false;
        let checkTotal = false;
        configObj.distributeWeightRelationList.forEach((item) => {
            // 非法字符检测
            if (isNaN(parseInt(item.distanceWeight)) || isNaN(parseInt(item.handlerWeight)) ||
                isNaN(parseInt(item.distributeNewCount)) ||
                isNaN(parseInt(item.serveScore)) || isNaN(parseInt(item.datumOrderHourRatio)) ||
                isNaN(parseInt(item.starLevelScoreWeight))) {
                checkNan = true;
            }
            // 正整数检测
            if (!isPositiveInteger(item.distanceWeight) || !isPositiveInteger(item.handlerWeight) ||
                !isPositiveInteger(item.distributeNewCount) ||
                !isPositiveInteger(item.serveScore) || !isPositiveInteger(item.datumOrderHourRatio) ||
                !isPositiveInteger(item.starLevelScoreWeight)) {
                checkNan = true;
            }
            if ((parseInt(item.distanceWeight) + parseInt(item.handlerWeight) +
                parseInt(item.distributeNewCount) + parseInt(item.serveScore) +
                parseInt(item.datumOrderHourRatio) + parseInt(item.starLevelScoreWeight)
            ) !== 100) {
                checkTotal = true;
            }
            let distributeWeightRelation = {
                relationId: parseInt(item.relationId),
                distanceWeight: parseInt(item.distanceWeight),
                handlerWeight: parseInt(item.handlerWeight),
                distributeNewCount: parseInt(item.distributeNewCount),
                serveScore: parseInt(item.serveScore),
                datumOrderHourRatio: parseInt(item.datumOrderHourRatio),
                starLevelScoreWeight: parseInt(item.starLevelScoreWeight),
                weightType: parseInt(item.weightType),
                distributeApplication: parseInt(item.distributeApplication),
                distributeConfigId: parseInt(item.distributeConfigId),
            }
            distributeWeightRelationList.push(distributeWeightRelation);
        });
        if (checkNan) {
            layer.msg('权重占比必须为0或正整数!');
            return false;
        }
        if (checkTotal) {
            layer.msg('权重占比之和必须等于100%');
            return false;
        }
        data.distributeWeightRelationList = distributeWeightRelationList;
        data.distributePlatId = parseInt(configObj.distributePlatId);
        data.distributeWay = parseInt(configObj.distributeWay);
        if (json.obj.distributeWay == 10) {
            data.provinceName = province.getValue()[0].name;
            data.cityName = city.getValue()[0].name;
        }
        var url = "";

        //distributePlatId为空是新增，先将数据存入缓存；distributePlatId不为空走更新，直接写入数据库
        if(configObj.distributePlatId==null||configObj.distributePlatId==undefined||configObj.distributePlatId==""){
            url = "/conf/distribute/plat/setSendOrderConfigDataToRedis";
            $http.save(url, data).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    // 跳转到返修单
                     element.tabChange('changeFirstTab', 'repairOrderId');
                    // 跳转到网格抢单
                    //element.tabChange('changeSecondTab', 'robOrderId');
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
                element.tabChange('changeSecondTab', 'robOrderId');
            });
        }else{
            data.distributePlatId=configObj.distributePlatId;
            data.autoStatusRework= configObj.autoStatusRework;
            data.reworkLimit =configObj.reworkLimit;
            url = "/conf/distribute/plat/modifyOrInsert"
            $http.save(url, data).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    // var index = parent.layer.getFrameIndex(window.name);
                    // parent.layer.close(index);
                    // window.parent.location.reload();
                    window.location.reload();
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
                element.tabChange('changeSecondTab', 'robOrderId');
            });
        }

        return false;
    });

    // 设置完成数据写入数据库
    form.on('submit(zmn-form-submit-to-database)', function (obj) {
        var data = obj.field;
        var robOrderData={};
        data.distributeWay=configObj.distributeWay;
        //目前仅针对啄木鸟平台
        data.plat=10;
        var url ="";
        var robOrderUrl="";
        //distributePlatId为空是新增，先将数据存入缓存；distributePlatId不为空走更新，直接写入数据库
        if(configObj.distributePlatId==null||configObj.distributePlatId==undefined||configObj.distributePlatId==""){
            //判断cityId是否为空，为空说明未设置抢单规则
            if(data.distributeWay==10){
                if(cityId == "" || cityId == undefined || cityId == null){
                    zmnUtils.layui.toastError("请先设置对应城市的抢单规则！");
                    element.tabChange('changeSecondTab', 'robOrderId');
                }
            }

            url = "/conf/distribute/plat/modifyOrInsert";
            robOrderUrl = "/conf/distribute/plat/robOrder/modifyOrInsert";
            data.cityId=cityId;
            data.cityName=cityName;
            robOrderData.cityId=cityId;
            robOrderData.cityName=cityName;
            robOrderData.distributeWay=configObj.distributeWay;
            robOrderData.plat=10;
            $http.save(robOrderUrl, robOrderData).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    $http.save(url, data).then(function () {
                        zmnUtils.layui.toastSuccess('成功', function () {
                            // var index = parent.layer.getFrameIndex(window.name);
                            // parent.layer.close(index);
                            // window.parent.location.reload();
                            window.location.reload();
                        })
                    }, function (msg) {
                        zmnUtils.layui.toastError(msg);
                    });
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
            });
        }else{
            configObj.autoStatusRework=data.autoStatusRework;
            configObj.reworkLimit=data.reworkLimit;
            configObj.reworkReminderLimit = data.reworkReminderLimit;
            url = "/conf/distribute/plat/modifyOrInsert";
            $http.save(url, configObj).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    // var index = parent.layer.getFrameIndex(window.name);
                    // parent.layer.close(index);
                    // window.parent.location.reload();
                    window.location.reload();
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
            });
        }

        return false;
    });

    form.on('switch(roundsEnable)', function (data) {
        if (this.checked) {
            // 解除禁用输入框
            $('#nonDirectCount').attr("disabled", false);
            $("#nonDirectCount").removeClass("layui-disabled").prop("disabled", false);
            $('#directSaleCount').attr("disabled", false);
            $("#directSaleCount").removeClass("layui-disabled").prop("disabled", false);
        } else {
            $('#nonDirectCount').attr("disabled", true);
            $("#nonDirectCount").addClass("layui-disabled").prop("disabled", true);
            $('#directSaleCount').attr("disabled", true);
            $("#directSaleCount").addClass("layui-disabled").prop("disabled", true);
        }
    });

// 新单简单派单和新单自动派单，不能同时设置为：关闭；
    form.on('switch(newSimpleStatus)',
        (data) => {
            var checkedValue = $('input[name="autoStatusNew"]:checked').val();
            if (1 == checkedValue) {
                layer.msg("新单简单派单和新单自动派单，不能同时设置为：关闭；");
                $("#newSimpleStatus").prop("checked", true);
                form.render();

            }
            if (3 == checkedValue) {
                layer.msg("当新单自动派单设置为“指定自动派”时，不可将新单简单派单设置为：关闭");
                $("#newSimpleStatus").prop("checked", true);
                form.render();
            }

            // 关闭新单简单派，使新单自动派不能勾选
            if (!data.elem.checked) {
                $("input[name='autoStatusNew'][value='1']").attr("disabled", "disabled");
                $("input[name='autoStatusNew'][value='3']").attr("disabled", "disabled");
                // $("input[name='autoStatusNew'][value='1']").addClass("layui-disabled");
                form.render();
            } else {
                $("input[name='autoStatusNew'][value='1']").removeAttr("disabled");
                $("input[name='autoStatusNew'][value='3']").removeAttr("disabled");
                form.render();
            }

        }
    );

    var timeStr = configObj.autoTimeStart == null ? '07:00 ~ 21:00' : (configObj.autoTimeStart + " ~ " + configObj.autoTimeEnd);
    let timeStrOfNoGrid = noGridRobOrderObj.cancelTimeEnd == null ? '00:00 ~ 08:00' : (noGridRobOrderObj.cancelTimeStart + " ~ " + noGridRobOrderObj.cancelTimeEnd);

//日期时间范围选择
    laydate.render({
        elem: '#autoTimeStr'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , value:timeStr
        , trigger: 'click'
    });

    laydate.render({
        elem: '#appointmentTimeStr'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , trigger: 'click'
    });
    laydate.render({
        elem: '#orderTimeStr'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , trigger: 'click'
    });
    laydate.render({
        elem: '#robOrderTimeStr'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , trigger: 'click'
    });
    laydate.render({
        elem: '#cancelTime'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , trigger: 'click'
        ,value: timeStrOfNoGrid
        ,done: function (value, date, endDate) {
            if (value !== '') {
                let spilt = value.split(" ~ ");
                let underLineTime = document.getElementById("underLineTime");
                underLineTime.innerText = spilt[1];
            }
        }
    });

    $('.chanping2').each(function () {
        laydate.render({
            elem: this,
            type: 'time',
            range: '~',
            format: 'HH:mm',
            trigger: 'click'
        });
    });


    table.init('zmn-table-1', {
        page: false
    });
    table.on('edit(zmn-table-1)', function (obj) {
        let value = obj.value; // 修改后的值
        let field = obj.field; //得到字段
        configObj.distributeWeightRelationList.forEach(r => {
            if (r.weightType == 1) {
                r[field] = value;
            }
        });
    });

    table.init('zmn-table-2', {
        page: false
    });
    table.on('edit(zmn-table-2)', function (obj) {
        let value = obj.value; // 修改后的值
        let field = obj.field; //得到字段
        /*configObj[field] = value;
        configObj.distributeWeightRelationList[1][field] = value;*/
        configObj.distributeWeightRelationList.forEach(r => {
            if (r.weightType == 2) {
                r[field] = value;
            }
        });
    });

    function dealRobOrderConfigData(data) {

        if (data.configId == undefined || data.configId == "" || data.configId == null) {
            return false;
        }
        let result = {};
        if(data.robOrderRelationList.length>1){
            var result2=data.robOrderRelationList[1];
            var orderTimeData = result2.orderTimeStart == null?'':result2.orderTimeStart+ " ~ "+result2.orderTimeEnd;
            var appointmentTimeData = result2.appointmentTimeStart == null?'':result2.appointmentTimeStart+ " ~ "+result2.appointmentTimeEnd;
            var robOrderTimeData = result2.robOrderTimeStart == null?'':result2.robOrderTimeStart+ " ~ "+result2.robOrderTimeEnd;
            var engineerTypeVal = result2.engineerType;
            var relationId = result2.relationId;
            $("#dynamic").append(initRuleNode(orderTimeData,appointmentTimeData,robOrderTimeData,engineerTypeVal,relationId));
            //最多两条规则
            $("#addRules").hide();
            drawTimePlug();
            if(data.robOrderRelationList!=null&&data.robOrderRelationList[0].robOrderRelationProductList!=null&&data.robOrderRelationList[0].robOrderRelationProductList.length>1){
                $(".productFlag").append(addProductsFunc());
                $(".addProducts").hide();
                drawSelect1();
            };
            //渲染下拉框
            drawSelect('edit');

            if(data.robOrderRelationList!=null&&data.robOrderRelationList[1].robOrderRelationProductList!=null&&data.robOrderRelationList[1].robOrderRelationProductList.length>1){
                $(".productFlag1").append(addProductsFunc1());
                $(".addProducts").hide();
                $(".addProducts1").hide();
                drawSelect3();
            }
        }else{
            if(data.robOrderRelationList!=null&&data.robOrderRelationList.length>0&&data.robOrderRelationList[0].robOrderRelationProductList!=null&&data.robOrderRelationList[0].robOrderRelationProductList.length>1){
                $(".productFlag").append(addProductsFunc());
                $(".addProducts").hide();
                drawSelect1();
            }else{
                $(".addProducts").show();
            }
            $("#addRules").show();
        }


        var result1=data.robOrderRelationList[0];
        if(result1!=undefined&&result1!=""&&result1!=null){
            var orderTimeData = result1.orderTimeStart == null?'':result1.orderTimeStart+ " ~ "+result1.orderTimeEnd;
            var appointmentTimeData = result1.appointmentTimeStart == null?'':result1.appointmentTimeStart+ " ~ "+result1.appointmentTimeEnd;
            var robOrderTimeData = result1.robOrderTimeStart == null?'':result1.robOrderTimeStart+ " ~ "+result1.robOrderTimeEnd;
            result.orderTimeStr =orderTimeData ;
            result.appointmentTimeStr =appointmentTimeData;
            result.robOrderTimeStr = robOrderTimeData;
            result.engineerType = result1.engineerType;
            result.relationId =result1.relationId;
        }
        form.val("zmn-rob-order-form", result);
    }

    /**
     * 1~99
     * @param val
     * @returns {boolean}
     */
    function isNumberAnd1To99(val){
        if(!val){
            return true;
        }
        let pattern = /^[0-9]*$/g;
        if (!pattern.test(val)) {
            return false;
        }
        let ruleValue = parseInt(val);
        let ruleValueBool = !isNaN(ruleValue);
        if (ruleValueBool && (ruleValue < 1 || ruleValue > 99)) {
            return false;
        }
        return true;
    }
    /**
     * 0~99
     * @param val
     * @returns {boolean}
     */
    function isNumberAnd0To99(val){
        if(!val){
            return true;
        }
        let pattern = /^[0-9]*$/g;
        if (!pattern.test(val)) {
            return false;
        }
        let ruleValue = parseInt(val);
        let ruleValueBool = !isNaN(ruleValue);
        if (ruleValueBool && (ruleValue < 1 || ruleValue > 99)) {
            return false;
        }
        return true;
    }

    let getters = {
        defaultField:'100',
        priorityProtectionTableId:'priorityProtectionTable', // 优先多伦 表格ID
        protectionTableId:'protectionTable', // 优先普通 表格ID
        getPriorityProtectionList: () => table.cache['priorityProtectionTable'], // 多伦
        getProtectionList: () => table.cache['protectionTable'], // 多伦
        getTableDataList: (tableId) => table.cache[tableId],
        getProtectionJSONStr : (tableId) => { // 多伦保护
            let protectionList = getters.getTableDataList(tableId);
            let jsonData = {};
            for (let item of protectionList) {
                let levelData = {};
                // 默认值
                let groupDefaultVal = item[getters.defaultField];
                if (groupDefaultVal && isNumberAnd1To99(groupDefaultVal)) {
                    levelData[getters.defaultField] = item[getters.defaultField];
                }
                for (let i = 0; i <= 10; i++) {
                    if(item[i] && isNumberAnd1To99(item[i])) {
                        levelData[i] = item[i];
                    }
                }
                if (Object.keys(levelData).length > 0) {
                    jsonData[item.productGroupId] = levelData;
                }
            }
            if (Object.keys(jsonData).length == 0) {
                return '';
            }
            return JSON.stringify(jsonData);
        },
        getProtectionTableData: (tableId, protectionGroupJson) => {
            let tableDataList = [];
            let protectionGroupData;
            // 兼容历史数据
            let isDefaultGroupData = false;
            if (protectionGroupJson) {
                protectionGroupData = JSON.parse(protectionGroupJson);
                isDefaultGroupData = !protectionGroupJson.includes(":{");
            }
            for (let productGroup of json.productGroupList) {
                let tableData = {
                    productGroupId: productGroup.value,
                    productGroupName: productGroup.label,
                    tableId: tableId
                };

                if (protectionGroupData) {
                    let protectionGroupLevel = protectionGroupData[productGroup.value];
                    if (protectionGroupLevel) {
                        if(isDefaultGroupData) {
                            // 兼容历史数据
                            tableData[getters.defaultField] = protectionGroupLevel[0];
                        } else {
                            for (let key of Object.keys(protectionGroupLevel)) {
                                tableData[key] = protectionGroupLevel[key];
                            }
                            tableData[getters.defaultField] = protectionGroupLevel[getters.defaultField];
                        }
                    }
                }

                tableDataList.push(tableData);
            }
            return tableDataList;
        },
        getFirstProtectionLevelsJsonStr: () => {
            // 获取首轮保护配置
            let levelData = {};
            $('.firstProtectionEngineerLevel select').each(function () {
                let that = $(this);
                levelData[that.data('group-id')] = that.val();
            });
            return JSON.stringify(levelData);
        },
        // 分组保护
        engineerLevelGroupTableId:'engineerLevelGroupTable', // 优先普通 表格ID
        getEngineerLevelGroupList: () => table.cache['engineerLevelGroupTable'], // 分组
        getEngineerLevelGroupListJsonStr: (engineerLevelGroupStatus) => { // 分组保护
            // 没有勾选提示
            let notCheckedData = {};
            $('.engineerLevelGroup:not(:checked):not(:disabled)').each(function (idx, item) {
                let that = $(this);
                notCheckedData[that.val()] = that.attr('title');
            });
            let vArr = Object.values(notCheckedData);
            let data = getters.getEngineerLevelGroupList();

            // 勾选分级保护，才强制校验
            if (engineerLevelGroupStatus == '2') {
                if (vArr.length > 0) {
                    return {
                        msg: vArr.reverse().join('，') + ' 等级工程师未配置！'
                    };
                }
                if (data.length < 2) {
                    return {
                        msg: '请至少配置2个工程师层级分组！'
                    };
                }
            }

            let engineerLevelGroupListJson = [];
            for (let item of data) {
                if (item.engineerLevels == '') {
                    return {
                        msg: '至少配置1个V等级工程师！'
                    }
                }
                if (item.protectionCount == '') {
                    return {
                        msg: '工程师层级分组保护单量不能为空！'
                    }
                }
                let obj = {
                    priority: item.priority,
                    engineerLevels: item.engineerLevels,
                    protectionCount: item.protectionCount == '-' ? 0 : item.protectionCount
                }
                engineerLevelGroupListJson.push(obj);
            }

            return {
                engineerLevelGroupListJsonStr: JSON.stringify(engineerLevelGroupListJson)
            }
        },
        getEngineerLevels : () => { // 分级准入
            let chkValue = [];
            $('input[name="engineerLevels"]:checked').each(function(){
                chkValue.push($(this).val());
            });
            return chkValue.join(",");
        },
        getDefaultEngineerLevelGroupListCurrentJsonData : () =>{
            let engineerLevelGroupListJson = [];
            if (json.obj.engineerLevelGroupListCurrentJson) {
                engineerLevelGroupListJson = JSON.parse(json.obj.engineerLevelGroupListCurrentJson);
                let lastData = engineerLevelGroupListJson[engineerLevelGroupListJson.length - 1];
                if (lastData.protectionCount == '0') {
                    lastData.protectionCount = '-';
                }
            }
            return engineerLevelGroupListJson;
        },
        getDefaultEngineerLevelGroupListJsonData : () =>{
            let engineerLevelGroupListJson = [];
            if (json.obj.engineerLevelGroupListJson) {
                engineerLevelGroupListJson = JSON.parse(json.obj.engineerLevelGroupListJson);
                let lastData = engineerLevelGroupListJson[engineerLevelGroupListJson.length - 1];
                if (lastData.protectionCount == '0') {
                    lastData.protectionCount = '-';
                }
            }
            return engineerLevelGroupListJson;
        }
    };

    /********************************分级保护 start****************************************************/
    form.on('checkbox(engineerLevelsFilter)', function (data) {
        if(!data.elem.checked){
            return;
        }
        $('input[name="engineerLevels"]').each(function (index, item) {
            let that = $(this);
            if (parseInt(that.val()) > parseInt(data.value)) {
                that.prop("checked", true);
            }
        })
        form.render();
    });
    /********************************分级保护 end****************************************************/

    /********************************多伦保护 start****************************************************/

    function initProtectionTable(tableId, defaultData) {
        let protectionTable = table.render({
            elem: '#' + tableId
            , cols: [[ //标题栏
                { field: 'productGroupId', type: 'checkbox', width:'0', hide: true },
                { field: 'productGroupName', title: '产品组', width: '100', align: 'center'},
                { field: '100', title: '快捷设置', edit:true, width: '70', align: 'center'},
                { field: 'usedAll', title: '应用所有V等级', width: '110', align: 'center', toolbar: '#usedAll'},
                { field: '0', title: 'V0', edit:true, width: '50', align: 'center'},
                { field: '1', title: 'V1', edit:true, width: '50', align: 'center'},
                { field: '2', title: 'V2', edit:true, width: '50', align: 'center'},
                { field: '3', title: 'V3', edit:true, width: '50', align: 'center'},
                { field: '4', title: 'V4', edit:true, width: '50', align: 'center'},
                { field: '5', title: 'V5', edit:true, width: '50', align: 'center'},
                { field: '6', title: 'V6', edit:true, width: '50', align: 'center'},
                { field: '7', title: 'V7', edit:true, width: '50', align: 'center'},
                { field: '8', title: 'V8', edit:true, width: '50', align: 'center'},
                { field: '9', title: 'V9', edit:true, width: '50', align: 'center'},
                { field: '10', title: 'V10', edit:true, width: '50', align: 'center'}
            ]]
            , data: defaultData
            , done: function (res, curr, count) {
            },
            page: false,
            limit: 1000,
            width:'845'
            , even: false
        });

        // 编辑事件处理
        table.on('edit('+tableId+')', function (obj) {
            if (!isNumberAnd1To99(obj.value)) {
                let list = getters.getTableDataList(obj.data.tableId);
                let trIndex = $(obj.tr).data('index');
                let data = list[trIndex];
                data[obj.field] = '';
                $(this).val('');
                table.reload(obj.data.tableId, {
                    data: list
                });
                layer.msg("请输入1-99范围内的整数");
            }
        });

        // 每行的应用所有
        form.on('switch(usedProtection)', function (obj) {
            let that = $(this);
            let tableId = that.data('table-id')
            let list = getters.getTableDataList(tableId);
            let trIndex = that.data('index');
            let data = list[trIndex];
            let defaultVal = data[getters.defaultField];
            if (!isNumberAnd1To99(defaultVal)) {
                return;
            }

            data.usedAll = obj.elem.checked;
            if (data.usedAll) {
                for (let i = 0; i <= 10; i++) {
                    data[i] = defaultVal;
                }
            }

            table.reload(tableId, {
                data: list
            });
        });

        /**
         * 勾选 应用到所有
         */
        form.on('checkbox(usedAllProtection)', function (obj) {
            if (!obj.elem.checked) {
                return;
            }

            let that = $(this);
            let id = that.data('id');
            let defaultVal = $(id).val();
            if (defaultVal == '') {
                return;
            }

            let tableId = that.data('table-id');
            let list = getters.getTableDataList(tableId);
            for (let item of list) {
                item[getters.defaultField] = defaultVal;
                for (let i = 0; i <= 10; i++) {
                    item[i] = defaultVal;
                }
            }
            table.reload(tableId, {
                data: list
            });
        });
    }
    /********************************多伦保护 end****************************************************/

    /********************************首伦保护 start****************************************************/
    function initProtectionFirstProductGroup(jsonData) {
        if (!jsonData) {
            return;
        }
        let levelGroupData = JSON.parse(jsonData);
        let $firstProtectionEngineerLevel = $('.firstProtectionEngineerLevel');
        for (let productGroup of json.productGroupList) {
            let selectVal = levelGroupData[productGroup.value];
            if (selectVal) {
                $firstProtectionEngineerLevel.find('select[data-group-id="' + productGroup.value + '"]').val(selectVal);
            }
        }

        form.render('select');
    }

    /********************************首伦保护 start****************************************************/

    // 首轮保护
    initProtectionFirstProductGroup(json.obj.protectionFirstProductGroupJson);

    // 多伦保护 - 多伦优先
    // json.obj.protectionTimesPriorityProductGroupJson = {"1013":{"0":"12","1":"12","2":"12","3":"12","4":"12","5":"12","6":"12","7":"12","8":"12","9":"12","10":"12"},"1016":{"0":"34","4":"23"}}
    let priorityProtectionTableData = getters.getProtectionTableData(getters.priorityProtectionTableId, json.obj.priorityProtectionTimesProductGroup);
    initProtectionTable(getters.priorityProtectionTableId, priorityProtectionTableData);

    // 多伦保护 - 多伦普通
    let protectionTableData = getters.getProtectionTableData(getters.protectionTableId, json.obj.protectionTimesProductGroupJson);
    initProtectionTable(getters.protectionTableId, protectionTableData);



    /***************************************分组保护 start*********************************************/

    // 分组保护配置 - 当前周期
    table.render({
        elem: '#engineerLevelGroupCurrentTable'
        , width: 650
        , cols: [[ //标题栏
            { type: 'checkbox', width:'0', hide: true }
            , { field: 'priority', title: '优先级', width: '60', align: 'center'}
            , {
                field: 'engineerLevels', title: '层级分组', width: '460', align: "center", templet: function (data) {
                    console.log(data);
                    if (!data.engineerLevels) {
                        return '';
                    }
                    return 'V' + data.engineerLevels.replaceAll(',', '、V');
                }
            }
            , { field: 'protectionCount', title: '多接单量', edit: true, unresize:true, width: '126', align: "center" }
        ]]
        , data: getters.getDefaultEngineerLevelGroupListCurrentJsonData()
        , done: function (res, curr, count) {
        }
        , even: false
        ,limit: 11 //每页默认显示的数量
    });


    var engineerLevelGroupTable = table.render({
        elem: '#engineerLevelGroupTable'
        , width: 801
        , cols: [[ //标题栏
            { type: 'checkbox', width:'0', hide: true }
            , { field: 'priority', title: '优先级', width: '60', align: 'center'}
            , { field: 'engineerLevels', title: '层级分组', width: '560', templet: '#engineerLevels', align: "center" }
            , { field: 'protectionCount', title: '下个周期多接单量', edit: true, unresize:true, width: '126', align: "center" }
            , { title: '操作', align: "center", toolbar: '#delBtn', width: '50' }
        ]]
        , data: getters.getDefaultEngineerLevelGroupListJsonData()
        , done: function (res, curr, count) {
            let tableView = this.elem.next(); // 当前表格渲染之后的视图
            let checkedEngineerLevelList = [];
            console.log(res.data);
            layui.each(res.data, function (i, item) {
                let $tr = tableView.find('tr[data-index=' + i + ']');
                console.log(item);
                if (!item.engineerLevels) {
                   return;
                }
                let arr = item.engineerLevels.split(',');
                checkedEngineerLevelList.push({
                    index: i,
                    engineerLevelArr: arr
                });
                for (let val of arr) {
                    $tr.find("input:checkbox[value='" + val + "']").attr('checked', 'true');
                }
            });

            // 设置 已选的其他 checkbox 禁用（如果就一行不处理）
            if (res.data.length > 1) {
                for (let item of checkedEngineerLevelList) {
                    for (let val of item.engineerLevelArr) {
                        tableView.find(".table-checkbox input:checkbox[index!='" + item.index + "'][value='" + val + "']").attr('disabled', 'disabled');
                    }
                }
            }

            form.render('checkbox');
        }
        , even: false
        ,limit: 11 //每页默认显示的数量
    });

    // 删除事件处理
    table.on('tool(engineerLevelGroupTable)', function (obj) {
        if (obj.event === 'del') {
            let engineerLevelGroupList = getters.getEngineerLevelGroupList();
            let index = obj.tr.data('index');
            engineerLevelGroupList.splice(index, 1); // 根据索引删除当前行
            for (let i = 0; i < engineerLevelGroupList.length; i++) {
                // 设置优先级
                let item = engineerLevelGroupList[i];
                item.priority = i + 1;
                if (item.protectionCount == '-') {
                    item.protectionCount = '';
                }
                if (i == engineerLevelGroupList.length - 1) {
                    item.protectionCount = '-';
                }
            }

            engineerLevelGroupTable.reload({
                data: engineerLevelGroupList
            });
        }
    });

    // 编辑事件处理
    table.on('edit(engineerLevelGroupTable)', function (obj) {
        let list = getters.getEngineerLevelGroupList();
        let trIndex = $(obj.tr).data('index');
        if (trIndex == list.length - 1) {
            let data = list[trIndex];
            data[obj.field] = '-';
            $(this).val('-');
            engineerLevelGroupTable.reload({
                data: list
            });
            layer.msg("不允许修改");
            return;
        }

        if (!isNumberAnd0To99(obj.value)) {
            let data = list[trIndex];
            data[obj.field] = '';
            $(this).val('');
            engineerLevelGroupTable.reload({
                data: list
            });
            layer.msg("请输入0-99范围内的整数");
        }
    });

    // 新增
    $("#addEngineerLevelGroup").on("click", function (obj) {
        let engineerLevelGroupList = getters.getEngineerLevelGroupList();
        if (engineerLevelGroupList.length >= 11) {
            layer.msg('最多添加11行');
            return;
        }
        if(engineerLevelGroupList.length > 0) {
            engineerLevelGroupList[engineerLevelGroupList.length-1].protectionCount = '';
        }
        let newData = {
            priority: engineerLevelGroupList.length + 1,
            engineerLevels: "",
            protectionCount: engineerLevelGroupList.length == 0 ? '' : '-'
        }
        engineerLevelGroupList.push(newData);
        engineerLevelGroupTable.reload({
            data: engineerLevelGroupList
        });
    });

    // 勾选
    form.on('checkbox(engineerLevelGroup)', function (data) {
        let selectElem = $(data.elem);
        let tdElem = selectElem.closest("td");
        let trElem = tdElem.closest("tr");
        let checkValue = [];
        trElem.find("input:checked").each(function () {
            checkValue.push($(this).val());
        });
        let engineerLevelGroupList = getters.getEngineerLevelGroupList();
        let item = engineerLevelGroupList[trElem.data("index")];
        item.engineerLevels = checkValue.length == 0 ? '' : checkValue.join(',');
        engineerLevelGroupTable.reload({
            data: engineerLevelGroupList
        });
    });

    /***************************************分组保护 end*********************************************/

    //对外暴露的接口
    exports('oms_conf_distribute_edit', {});
})
;